package cn.hx.mall.permissions.service.impl;

import cn.hx.mall.permissions.dao.RoleDao;
import cn.hx.mall.permissions.entity.Role;
import cn.hx.mall.permissions.entity.page.Page;
import cn.hx.mall.permissions.service.RoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 后台用户角色表(Role)表服务实现类
 *
 * @author makejava
 * @since 2022-11-02 17:02:39
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleDao roleDao;

    @Override
    public List<Role> queryLikeName(String name) {
        Role role=new Role();
        String name1="%"+name+"%";
        role.setName(name1);
        return roleDao.queryAll(role);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Role queryById(Long id) {
        return this.roleDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Role> queryAllByLimit(Role role,int offset, int limit) {
        offset=(offset-1)*limit;
        return this.roleDao.queryAllByLimit(role,offset, limit);
    }

    /**
     * 新增数据
     *
     * @param role 实例对象
     * @return 实例对象
     */
    @Override
    public Role insert(Role role) {
        this.roleDao.insert(role);
        return role;
    }

    /**
     * 修改数据
     *
     * @param role 实例对象
     * @return 实例对象
     */
    @Override
    public Role update(Role role) {
        this.roleDao.update(role);
        return this.queryById(role.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.roleDao.deleteById(id) > 0;
    }


    @Override
    public void deleteResourcesByRoleId(Integer roleId) {
        this.roleDao.deleteResourcesByRoleId(roleId);
    }

    @Override
    public void allocResources(Integer roleId, List<String> ids1) {
        for (String s : ids1) {
            roleDao.allocResources(roleId,Integer.valueOf(s));
        }

    }

    @Override
    public Page getPageInfo(Page page) {
        if(page.getPage()==null){
            page.setPage(1);
        }if(page.getLimit()==null){
            page.setLimit(10);
        }
        Role role = new Role();
        role.setName(page.getSearch());
        int count = roleDao.count(role);
        int size = page.getLimit();
        int cntPage = count%size==0?count/size:(count/size+1);
        page.setCntpage(cntPage);
        page.setCount(count);
        return page;
    }

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }
}